﻿using Ndns.Cache;
using Ndns.ServerHost.Abstractions;
using Ndns.ServerHost.Abstractions.Services;
using System;

namespace Ndns.ServerHost.Builder
{
    public static class DnsCacheMiddlewareBuilder
    {
        public static IServiceBuilder AddMemoryCache(this IServiceBuilder services, DnsCacheOptions options)
        {
            if (services == null)
                throw new ArgumentNullException(nameof(services));

            services.Add(typeof(ICacheService), new DnsCacheServiceImpl(options));

            return services;
        }
        public static IServiceBuilder AddMemoryCache(this IServiceBuilder services, DnsCacheOptions options, CacheCompactCallback compactCallback, CacheCompactCallback expirationCallback)
        {
            if (services == null)
                throw new ArgumentNullException(nameof(services));

            var cache = new DnsCacheServiceImpl(options);
            if (compactCallback != null)
            {
                cache.AttachCompactCallback(compactCallback);
            }
            if (expirationCallback != null)
            {
                cache.AttachExpirationCallback(expirationCallback);
            }

            services.Add(typeof(ICacheService), cache);

            return services;
        }

        public static IMiddlewaresBuilder UseMemoryCache(this IMiddlewaresBuilder builder)
        {
            if (builder == null)
                throw new ArgumentNullException(nameof(builder));

            builder.Use(new DnsCacheMiddleware());

            return builder;
        }
    }
}
